<template>
  <tl-sub-page :render="render" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer editPage" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <div class="mpm-project-container">
      <div style="width:0px;overflow:hidden;height:0px;"><input type="text" /></div>
      <div class="mpm-project-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_review_edit.png" class="logo" style="width: 55px;height: 55px" />
          <div class="content" :title="model.projectname">
            <p>
              <b v-if="model.id || projectinfo.projectcode">{{ model.projectname + '-' }}</b>
              <b>项目复盘</b>
            </p>
            <p class="light">
              <span>项目经理：{{ model.applyusername ? model.applyusername + '【' + model.applyusercode + '】' : user.name + '【' + user.code + '】' }}</span>
              <span>创建时间：{{ model.createon ? formatDate(model.createon) : formatDate(new Date()) }}</span>
              <span v-if="model.dispprojectlevel">项目级别：{{ model.dispprojectlevel }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar">
          <el-button type="danger" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="mpm-project-nav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list">
          <template v-for="item in navList">
            <li :key="item.code" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 150px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <div class="mpm-project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="mpm-project-main-container" id="mpmMainContainer">
          <div v-if="extraParam === 'ReviewBid'">
            <div style="margin-top: 10px;">
              <label style="font-size: 16px; color: red;margin-left: 27px;">请核查“四张表”获取情况是否准确无误。</label>
            </div>
          </div>
          <div style="padding:0 10px">
            <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
              <a id="basic" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                基本信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="Sponsor" prop="sponsorcode">
                    <tl-ref-user v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" :disabled="true" dataType="code" :singleSelect="true"> </tl-ref-user>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="Owner" prop="ownercode" :rules="rules.validateRequire">
                    <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" :disabled="true" dataType="code" :singleSelect="true"> </tl-ref-user>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目结果" prop="projectresult" :rules="rules.validateRequire">
                    <el-select v-model="model.projectresult" filterable clearable @change="setWinBidInfo">
                      <el-option v-for="item in mpmprojectresultList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结果公布时间" prop="resulttime" :rules="bidResultProject && !noBidState ? rules.validateRequire : []">
                    <el-date-picker v-model="model.resulttime" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" :disabled="!(canEditBidInfo || moreBidDate || !bidResultProject)"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="可参与金额" prop="participatemoney" :rules="rules.validateRequire">
                    <el-input-number v-model="model.participatemoney" controls-position="right" :step="1" :min="0" :precision="2" class="unitInputNumber" :disabled="true"></el-input-number>
                    <span class="unitSpan">万元</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结项金额" prop="settlementmoney" :rules="model.projectresult === '1' && !noBidState ? rules.validateRequire : []">
                    <el-input-number v-model="model.settlementmoney" controls-position="right" :step="1" :min="0" :precision="2" class="unitInputNumber" :disabled="disableSettleMoney"></el-input-number>
                    <span class="unitSpan">万元</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="结项说明" prop="projectdescription" :rules="rules.validateRequire">
                    <el-input v-model="model.projectdescription" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="result" class="step-position">&nbsp;</a>
              <el-form :disabled="disableEditSubmit || disableSave" v-if="!noBidState">
                <mpm-project-win-bid-info-ref ref="winBidInfoRef" :disableSave="disableSave" :projectcode="model.projectcode" :reviewid="model.id" :model="model" style="margin-bottom: 20px" @setWinBidInfo="setWinBidInfo"></mpm-project-win-bid-info-ref>
              </el-form>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目目标" prop="target">
                    <el-input v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目成果" prop="actualresult" :rules="rules.validateRequire">
                    <el-input v-model="model.actualresult" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="差异分析" prop="differenceanalysis" :rules="rules.validateRequire">
                    <el-input v-model="model.differenceanalysis" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注" prop="description">
                    <el-input v-model="model.description" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div v-if="!noBidState">
                <a id="fourpage" class="step-position">&nbsp;</a>
                <div class="tl-form-line-title">
                  四张表获取情况
                </div>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="本次评标专家名单" prop="thisbidlist" :rules="rules.validateRequire">
                      <el-select v-model="model.thisbidlist" filterable clearable :disabled="alevelBid" @change="changeFour">
                        <el-option v-for="item in codeModel.mpmthisbidList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="标杆对标" prop="bidmark" :rules="rules.validateRequire">
                      <el-select v-model="model.bidmark" filterable clearable :disabled="alevelBid" @change="changeFour">
                        <el-option v-for="item in codeModel.mpmbidmarkList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="1">
                    <el-tooltip content="至少获取中标厂家前三名标书" placement="top" style="font-size:20px; margin-top:4px; padding-left: 5px">
                      <i class="el-icon-info" style="color: #909399"/>
                    </el-tooltip>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="11">
                    <el-form-item label="细项得分" prop="smallbidscore" :rules="rules.validateRequire">
                      <el-select v-model="model.smallbidscore" filterable clearable @change="changeSmallBidScore" :disabled="alevelBid">
                        <el-option v-for="item in codeModel.mpmsmallbidscoreList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="1">
                    <el-tooltip content="所有中标厂家细项得分" placement="top" style="font-size:20px; margin-top:4px; padding-left: 5px">
                      <i class="el-icon-info" style="color: #909399"/>
                    </el-tooltip>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="专家库名单" prop="expertlist" :rules="rules.validateRequire">
                      <el-select v-model="model.expertlist" filterable clearable :disabled="alevelBid" @change="changeFour">
                        <el-option v-for="item in codeModel.mpmexpertList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="四张表未全部获取原因分析" prop="fourpagereason" :rules="rules.validateRequire" v-if="showFourPageReason">
                      <el-input v-model="model.fourpagereason" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <div v-if="!noBidState">
                <a id="biddetail" class="step-position">&nbsp;</a>
                <div class="tl-form-line-title">
                  评分细则
                </div>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="自评情况" prop="havebidscoredata">
                      <el-select v-model="model.havebidscoredata" filterable clearable disabled>
                        <el-option v-for="item in codeModel.mpmreviewbidscoreList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="本次评标得分获取情况" prop="thisbidscore" :rules="rules.validateRequire" label-width="200px">
                      <el-select v-model="model.thisbidscore" filterable clearable>
                        <el-option v-for="item in codeModel.mpmreviewthisbidscoreList" :key="item.code" :label="item.name" :value="item.code" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="运行质量得分" prop="qualityscore" v-if="nanwangProject">
                      <el-input v-model="model.qualityscore" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,1}/)"></el-input>
                      <span class="unitSpan">分</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="资质能力审核得分" prop="abilityscore" v-if="nanwangProject" label-width="200px">
                      <el-input v-model="model.abilityscore" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,1}/)"></el-input>
                      <span class="unitSpan">分</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="两次自评均未完成原因分析" prop="unfinishoneortwo" :rules="rules.validateRequire" v-if="model.havebidscoredata === '4'">
                      <el-input v-model="model.unfinishoneortwo" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="未完成第一次自评原因分析" prop="unfinishoneortwo" :rules="rules.validateRequire" v-if="model.havebidscoredata === '3'">
                      <el-input v-model="model.unfinishoneortwo" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="未完成第二次自评原因分析" prop="unfinishoneortwo" :rules="rules.validateRequire" v-if="model.havebidscoredata === '2'">
                      <el-input v-model="model.unfinishoneortwo" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <mpm-project-bid-score-ref ref="bidScore1" :times="'3'" :editdisabled="!disableSave" :type="'1'" :projectinfo="projectinfo" :title="'商务'" :fromReview="true"></mpm-project-bid-score-ref>
                    <mpm-project-bid-score-ref ref="bidScore2" :times="'3'" :editdisabled="!disableSave" :type="'2'" :projectinfo="projectinfo" :title="'技术'" :fromReview="true"></mpm-project-bid-score-ref>
                    <tl-offer :ref="'line5'" :times="'3'" :editable="!disableSave" :type="'3'" :projectinfo="projectinfo" :title="'报价'" :showgapanalysis="true"></tl-offer>
                  </el-col>
                </el-row>
              </div>
              <a id="processAnalysis" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                过程分析
              </div>
              <el-row>
                <el-col :span="18">
                  <el-form-item label="里程碑及任务总结" :rules="rules.validateRequire"> </el-form-item>
                </el-col>
                <el-col :span="6">
                  <div class="text-hover" style="float: right;fontSize: 14px;margin: 6px" @click="openProcessAnalyse">全屏展示</div>
                </el-col>
              </el-row>
              <el-form :disabled="disableEditSubmit || disableSave">
                <mpm-project-milepost-ref style="margin-bottom: 30px" ref="milePostRef" :model="model" @fullScreen="openProcessAnalyse"></mpm-project-milepost-ref>
              </el-form>
              <a id="summary" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                经验与教训
              </div>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目经验" prop="projectexp" :rules="rules.validateRequire">
                    <el-input v-model="model.projectexp" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="项目教训" prop="projectlesson" :rules="rules.validateRequire">
                    <el-input v-model="model.projectlesson" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <a id="judge" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                项目成员评价
              </div>
              <mpm-project-performance-index ref="performanceRef" :model="model"></mpm-project-performance-index>
              <a id="apply" class="step-position">&nbsp;</a>
              <div class="tl-form-line-title">
                申请信息
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请部门" prop="applydeptname">
                    <tl-ref-dept v-model="model.applydeptcode" :initDisplayData.sync="model.applydeptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{ qry_enabled: 1 }"></tl-ref-dept>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请公司" prop="applyorgname">
                    <el-input v-model="model.applyorgname" :readonly="true" class="is-disabled"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="applyusername">
                    <tl-ref-user v-model="model.applyusername" :initDisplayData.sync="model.applyusername" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="applyusercode">
                    <el-input v-model="model.applyusercode" :readonly="true" class="is-disabled"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="单据日期" prop="docdate">
                    <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd" disabled></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="提交时间" prop="submitdate">
                    <el-date-picker v-model="model.submitdate" type="date" placeholder="提交时间" value-format="yyyy-MM-dd" disabled></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="审批流程" prop="flowid">
                    <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="state">
                    <el-input v-model="model.dispstate" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer" style="float:right;margin-top:10px">
              <el-button @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave" icon="el-icon-document-checked" type="primary">保存</el-button>
              <el-button @click="projectSubmit" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval" type="primary"> <svg-icon icon-class="send" />提交审批 </el-button>
              <tl-attachment ref="attachmentRef" sourceType="MpmProjectReview" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit || this.uiOperateState === '3'">
                <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
              </tl-attachment>
              <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="primary"> <svg-icon icon-class="list" />审批历史 </el-button>
              <el-button @click="doDelApproval" v-if="!disableEditSubmit" :disabled="disableDelApproval" type="primary"> <svg-icon icon-class="undo" />审批退回 </el-button>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <tl-approval-history ref="history" sourceType="MpmProjectReview" :sourceId="model.id" />
    <mpm-project-milepost-ref style="margin-bottom: 30px" ref="milePostDialogRef" :model="model" :render="'el-dialog'" :el-table-height="null" @refresh="refreshProcessAnalyse" :disabled="disableEditSubmit || disableSave"></mpm-project-milepost-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit_edit } from '../../../mixins/mixin_approval_edit'
import { validateNull } from '@tapui/utils/validate'
/** 子组件 */
import MpmProjectWinBidInfoRef from '../mpmProjectWinBidInfo/indexnew'
import MpmProjectMilepostRef from '../mpmProjectMilepost/indexComp'
import MpmProjectBidDetailRef from '../mpmProjectReviewBidDetail/indexComp'
import MpmProjectBidScoreRef from '../mpmProjectBidScore/indexFrame'
import MpmProjectPerformanceIndex from '../mpmProjectPerformanceJudge/indexComp'
import tlOffer from '../mpmProjectBidScore/indexFrameOffer'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate } from '@tapui/utils/date'
import { Mpm_Nanwang_Dept } from '@/const/const'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit_edit],
  components: { MpmProjectMilepostRef, MpmProjectWinBidInfoRef, MpmProjectBidDetailRef, MpmProjectBidScoreRef, MpmProjectPerformanceIndex, tlOffer },
  data() {
    return {
      moduleTitle: '项目复盘结项',
      urlPrefix: '/mpm/projectReview/',
      isQueryOnCreated: false,
      externalQueryParamForPool: {},
      mainHeight: 1000,
      navList: [{ name: '基本信息', on: true, code: 'basic' }, { name: '结果分析', on: false, code: 'result' }, { name: '四张表获取情况', on: false, code: 'fourpage' }, { name: '评分细则', on: false, code: 'biddetail' }, { name: '过程分析', on: false, code: 'processAnalysis' }, { name: '经验与教训', on: false, code: 'summary' }, { name: '项目成员评价', on: false, code: 'judge' }, { name: '申请信息', on: false, code: 'apply' }],
      url: {
        // 额外的url
        meetList: process.env.MEET_API + '/meet/meetManage/list',
        getBidGuideInfo: '/mpm/projectReview/getBidGuideInfo',
        generatePerformance: '/mpm/projectPerformanceJudge/generatePerformance',
        queryScoreTimes: 'mpm/projectBidScore/queryScoreTimes',
        queryPMoProjectType: 'mpm/project/list',
        queryReviewMeetInfo: '/mpm/projectReview/queryReviewMeetInfo'
      },
      meetTypeList: [],
      dialogVisible: false,
      PMOType: '',
      moreBidDate: false,
      canEditBidInfo: false,
      connectBid: false,
      extraParam: ''
    }
  },
  props: {
    // 当前元素展示方式。默认为dialog，可选div/el-drawer
    render: {
      default: 'el-drawer',
      type: String
    },
    projectinfo: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  computed: {
    // 禁用审批按钮
    disableApproval() {
      return (this.stateApproval && this.model.state !== 2) || this.uiOperateState === 4
    },
    disableSettleMoney() {
      return validateNull(this.model.projectresult) || this.model.projectresult === '2' || this.model.projectresult === '3' || this.model.projectresult === '4' || this.model.projectresult === '8' || this.model.projectresult === '6' || this.model.projectresult === '7'
    },
    mpmprojectresultList() {
      let result = []
      if (this.PMOType === '0') {
        // 推广类
        result = this.codeModel.mpmprojectresultList.slice(8, 11)
        return result
      }
      if (this.codeModel.hasOwnProperty('mpmprojectresultList')) {
        if (this.model.purchasepattern === '14' || this.model.purchasepattern === '15') {
          result = this.codeModel.mpmprojectresultList.slice(5, 8)
          return result
        } else if (this.model.purchasepattern === '11' || this.model.purchasepattern === '12' || this.model.purchasepattern === '13') {
          result = this.codeModel.mpmprojectresultList.slice(0, 5)
          return result
        } else {
          result = this.codeModel.mpmprojectresultList.slice(0, 8)
          return result
        }
      } else {
        return []
      }
    },
    // 非招标项目(采购模式为非招标、其他)
    noBidState() {
      return this.model.purchasepattern === '14' || this.model.purchasepattern === '15'
    },
    // 南网省份项目
    nanwangProject() {
      return Mpm_Nanwang_Dept.indexOf(',' + this.model.deptcommoncode + ',') > -1
    },
    // 中标、未中标项目
    bidResultProject() {
      return this.model.projectresult === '1' || this.model.projectresult === '2'
    },
    // 展示四张表页面
    showFourPageReason() {
      return this.model.thisbidlist === '2' || this.model.thisbidlist === '3' || this.model.bidmark === '2' || this.model.bidmark === '3' || this.model.smallbidscore === '2' || this.model.smallbidscore === '3' || this.model.expertlist === '2' || this.model.expertlist === '3'
    },
    alevelBid() {
      return this.model.projectlevel === '0' && (this.model.purchasepattern === '11' || this.model.purchasepattern === '12' || this.model.purchasepattern === '13')
    }
  },
  methods: {
    changeSmallBidScore(data) {
      if (data === '1') {
        this.$set(this.model, 'thisbidscore', '1')
      }
      if (data === '2') {
        this.$set(this.model, 'thisbidscore', '')
      }
      if (data === '3') {
        this.$set(this.model, 'thisbidscore', '3')
      }
      if (!this.showFourPageReason) {
        this.$set(this.model, 'fourpagereason', '')
      }
    },
    changeFour() {
      if (!this.showFourPageReason) {
        this.$set(this.model, 'fourpagereason', '')
      }
    },
    openProcessAnalyse() {
      this.$refs.milePostDialogRef.open()
    },
    refreshProcessAnalyse() {
      this.$refs.milePostRef.doQuery()
    },
    async doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      if (!this.noBidState && this.$refs.line5) {
        await this.$refs.line5.doSave()
      }
      if (this.isAdd) {
        this.doAdd()
      } else {
        this.doEdit()
      }
    },
    async projectSubmit() {
      let that = this
      that.submitLoading = true
      that.$refs.form.validate(async (valid, res) => {
        if (valid) {
          if (!this.noBidState && this.$refs.line5) {
            await this.$refs.line5.doSave()
          }
          let saveresult = await that.addBase()
          if (saveresult) {
            // let record = await that.recordUpload()
            // if (!record) {
            //   this.submitLoading = false
            //   this.saveLoading = false
            //   return
            // }
            let approvalResult = await that.beforeApproval()
            if (!approvalResult) {
              this.submitLoading = false
              this.saveLoading = false
              return
            }
            this.submitLoading = true
            this.saveLoading = true
            const parameter = { id: that.model.id }
            putAction(that.url.submit, that.model)
              .then((res) => {
                if (res.success) {
                  that.queryData(that.model.id).then((_) => {
                    that.loaded()
                    that.saveLoading = false
                    that.submitLoading = false
                  })
                  that.$tap.alert('提交审批成功', 'success')
                } else {
                  that.$tap.alert(res.message, 'warning')
                  that.saveLoading = false
                  that.submitLoading = false
                }
              })
              .catch((err) => {
                that.saveLoading = false
                that.submitLoading = false
              })
          }
        } else {
          that.submitLoading = false
          that.$tap.alert('按要求填写表单数据项，包括必填项，数据格式等')
        }
      })
    },
    /** 抽屉组件必有 **/
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100 - (this.isApproval ? 110 : 0)
    },
    /** 抽屉组件必有 **/
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    /** 抽屉组件必有 **/
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd')
    },
    /** 点击左侧导航，抽屉组件必有 **/
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      this.mainScrollElement.addEventListener('scroll', () => {
        let currentTop = this.mainScrollElement.scrollTop
        let code = ''
        for (let element of document.getElementsByClassName('step-position')) {
          if (element.getBoundingClientRect().y >= 0) {
            code = element.id
            break
          }
        }
        this.navList.forEach((m) => {
          if (m.code === code) {
            m.on = true
          } else {
            m.on = false
          }
        })
      })
    },
    /** 抽屉组件必重写，主要为了执行resizeHandler方法、给mainScrollElement赋值，并添加监听事件，不要直接复制该方法 **/
    open() {
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.$refs.form.clearValidate()
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.$refs.form.clearValidate()
            this.loaded()
          })
        }
        this.mainScrollElement = document.getElementById('mpmMainContainer').getElementsByClassName('el-scrollbar__wrap')[0]
        this.onMainScroll()
      })
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.assignModel()
        // 保存新增单据，加载中标子表信息
        this.doSubmitEdit()
      }
    },
    assignModel() {
      this.$set(this.model, 'docdate', new Date())
      this.$set(this.model, 'applyusername', this.user.name)
      this.$set(this.model, 'applyusercode', this.user.code)
      this.$set(this.model, 'applydeptcode', this.dept.code)
      this.$set(this.model, 'applydeptname', this.dept.fullname)
      this.$set(this.model, 'applyorgcode', this.org.code)
      this.$set(this.model, 'applyorgname', this.org.name)
      this.$set(this.model, 'usercode', this.user.code)
      this.$set(this.model, 'username', this.user.name)
      this.$set(this.model, 'sponsor', this.projectinfo.sponsor)
      this.$set(this.model, 'sponsorcode', this.projectinfo.sponsorcode)
      this.$set(this.model, 'projectid', this.projectinfo.id)
      this.$set(this.model, 'projectname', this.projectinfo.projectname)
      this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
      this.$set(this.model, 'deptcode', this.projectinfo.deptcode)
      this.$set(this.model, 'owner', this.projectinfo.owner)
      this.$set(this.model, 'ownercode', this.projectinfo.ownercode)
      this.$set(this.model, 'deptcommoncode', this.projectinfo.deptcommoncode)
      this.$set(this.model, 'participatemoney', this.projectinfo.participatemoney)
      this.$set(this.model, 'purchasepattern', this.projectinfo.purchasepattern)
      this.$set(this.model, 'target', this.projectinfo.target)
      this.$set(this.model, 'reviewflag', 0)
    },
    async queryScoreTimes() {
      if (this.model.havebidscoredata) {
        return
      }
      let result = await getAction(this.url.queryScoreTimes, { projectCode: this.model.projectcode })
      if (result.success) {
        this.$set(this.model, 'havebidscoredata', result.result.toString())
      }
    },
    loaded() {
      if (!this.isAdd && !this.noBidState) {
        this.queryScoreTimes()
      }
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
      // 如果为非招标项目，隐藏结果分析、评分细则左侧tab
      if (this.noBidState) {
        this.navList = [{ name: '基本信息', on: true, code: 'basic' }, { name: '过程分析', on: false, code: 'processAnalysis' }, { name: '经验与教训', on: false, code: 'summary' }, { name: '申请信息', on: false, code: 'apply' }]
      }
      // 删除新模板中不使用的字段，将reviewflag改为0,即新数据
      if (this.model.id && (this.model.state === 0 || this.model.state === 2) && this.model.reviewflag !== 0) {
        this.clearOldReview()
      }
      // 从投标拉取中标信息
      if (this.model.id && !this.noBidState) {
        this.getBidGuideInfo()
      }
      // 加载里程碑及任务信息和评分细则信息、组员绩效评价信息
      if (this.model.projectcode && this.model.id) {
        this.$set(this.projectinfo, 'projectcode', this.model.projectcode)
        this.$refs.milePostRef.doQuery()
        if (!this.noBidState) {
          this.$refs.bidScore1.doQuery()
          this.$refs.bidScore2.doQuery()
          this.$refs.line5.doQuery()
        }
      }
      // 加载绩效评价信息,如果状态为开立和退回，判断是否需要生成评价信息，兼容老单据
      if (this.model.state === 0 || this.model.state === 2) {
        getAction(this.url.generatePerformance, { projectcode: this.model.projectcode }).then((res) => {
          if (res.success) {
            this.$refs.performanceRef.doQuery()
          }
        })
      } else {
        this.$refs.performanceRef.doQuery()
      }
      // 查询项目类型（销售类、推广类）
      if (this.model.projectcode) {
        let queryParam1 = { sidx: 'createon', sord: 'desc', pageSize: 10, currentPage: 1 }
        queryParam1.qry_projectcode = this.model.projectcode
        getAction(this.url.queryPMoProjectType, queryParam1).then((res) => {
          if (res.success) {
            this.PMOType = res.result.dataList[0].pmoprojecttype
          }
        })
      }
      // 若为不可编辑状态则清空placeholder
      if (this.disableEditSubmit || this.disableSave) {
        this.$refs.form.fields.forEach((item) => {
          if (item.$children[1].$options._componentTag === 'el-input') {
            item.$children[1].getInput().placeholder = ''
          }
        })
      }
      // A级招标项目四张表内容为全部获取
      if (this.alevelBid) {
        this.$set(this.model, 'thisbidlist', '1')
        this.$set(this.model, 'bidmark', '1')
        this.$set(this.model, 'smallbidscore', '1')
        this.$set(this.model, 'expertlist', '1')
        this.$set(this.model, 'thisbidscore', '1')
      }
      // 正常/异常结项判定
      this.aftergetproject()
      this.$refs.form.clearValidate()
    },
    // 当中标信息、中标结果变化时，修改结果公布时间，结项金额
    setWinBidInfo() {
      this.moreBidDate = false
      this.canEditBidInfo = false
      if (!this.bidResultProject || this.noBidState) {
        this.$set(this.model, 'resulttime', null)
        this.$set(this.model, 'settlementmoney', 0)
        return
      }
      // 中标、未中标的招标项目，如果无法自动带出中标信息，中标公告时间和结项金额由用户填写
      let winInfo = this.$refs.winBidInfoRef.datas.filter(item => !validateNull(item.bulletintime) && !validateNull(item.bidwinfund))
      if (winInfo.length === 0) {
        this.canEditBidInfo = true
        if (this.model.projectresult === '2') {
          this.$set(this.model, 'settlementmoney', 0)
        }
      } else {
        // 中标、未中标项目，结果公布时间为中标结果信息里的“中标结果公示时间”，多个取次数最多，其次最晚
        this.setBulletinTime(winInfo)
        this.setBidWinFund(winInfo)
      }
    },
    // 获取中标结果时间
    setBulletinTime(winInfo) {
      if (winInfo.length === 1) {
        this.$set(this.model, 'resulttime', winInfo[0].bulletintime)
      } else {
        this.moreBidDate = true
        winInfo.sort((a, b) => Date.parse(b.bulletintime) - Date.parse(a.bulletintime))
          let maxName
          let maxNum = 0
          let res = winInfo.map(item => item.bulletintime).reduce((res, currentNum) => {
            res[currentNum] ? res[currentNum] += 1 : res[currentNum] = 1
            if (res[currentNum] > maxNum) {
              maxNum = res[currentNum]
              maxName = currentNum
            }
            return res
          }, {})
          this.$set(this.model, 'resulttime', maxName)
      }
    },
    // 获取结项金额
    setBidWinFund(winInfo) {
      if (this.model.projectresult === '2') {
        this.$set(this.model, 'settlementmoney', 0)
      } else {
        let bidArr = winInfo.filter(item => item.bidresult === '1').map(item => Number(item.bidwinfund).toFixed(2))
        let settlemoney = 0
        bidArr.forEach(item => {
          settlemoney += parseFloat(item)
        })
        this.$set(this.model, 'settlementmoney', settlemoney)
      }
    },
    // 获取复盘会开启信息
    async queryReviewMeetInfo() {
      let param = {
        qry_projectcode: this.model.projectcode
      }
      return await postAction(this.url.queryReviewMeetInfo, param).then(res => {
        if (res.success) {
          return res.result
        }
      })
    },
    async beforeApproval() {
      // 项目为中标、未中标、弃标且为招标类项目时，重新拉取中标信息，如果关联了招标项目但是没有中标信息，需要到投标系统录入
      if ((this.bidResultProject || this.model.projectresult === '3') && !this.noBidState) {
        await this.getBidGuideInfo()
        if (this.connectBid) {
          this.$tap.alert('销售项目关联的投标申请尚未录入中标信息，请联系招投标管理部录入！', 'warning')
          return false
        }
      }
      // A&B级项目复盘报告中项目结果为“中标”、“未中标”且为中标类项目，判断是否已召开复盘会且会议纪要是否已上传
      if (this.bidResultProject && (this.model.projectlevel === '0' || this.model.projectlevel === '1') && !this.noBidState) {
        let meetFlag = await this.queryReviewMeetInfo()
        if (!meetFlag) {
          this.$tap.alert('请先在沟通模块创建“销售项目会议-复盘会”，并上传会议纪要或录音。', 'warning')
          return false
        }
      }
      // 正常结项的项目，中标需要上传中标通知书或合同扫描件，未中标需要上传中标公告截图
      if (this.model.endtype === '0') {
        if (this.model.projectresult === '1' && this.$refs.attachmentRef.fileCount <= 0 && this.$refs.attachmentRef.fileList.length <= 0) {
          this.$tap.alert('请上传中标通知书或合同扫描件！', 'warning')
          this.submitLoading = false
          return false
        } else if (this.model.projectresult === '2' && this.$refs.attachmentRef.fileCount <= 0 && this.$refs.attachmentRef.fileList.length <= 0) {
          this.$tap.alert('请上传中标公告截图！', 'warning')
          this.submitLoading = false
          return false
        }
      }
      // 第一次自评
      if (!this.noBidState) {
        if (!validateNull(this.$refs.bidScore1.datas) && this.$refs.bidScore1.datas.length > 0) {
          let tempData = this.$refs.bidScore1.datas
          for (let temp of tempData) {
            if (validateNull(temp.feedbackscore) || validateNull(temp.losspointandadvice)) {
              this.$tap.alert('评标细则-商务须填写专家反馈得分、失分点及改进意见！', 'warning')
              this.submitLoading = false
              return false
            }
          }
        }
        if (!validateNull(this.$refs.bidScore2.datas) && this.$refs.bidScore2.datas.length > 0) {
          let tempData = this.$refs.bidScore2.datas
          for (let temp of tempData) {
            if (validateNull(temp.feedbackscore) || validateNull(temp.losspointandadvice)) {
              this.$tap.alert('评标细则-技术须填写专家反馈得分、失分点及改进意见！', 'warning')
              this.submitLoading = false
              return false
            }
          }
        }
      }
      // 绩效打分必填
      if (!validateNull(this.$refs.performanceRef.datas) && this.$refs.performanceRef.datas.length > 0) {
        for (let temp of this.$refs.performanceRef.datas) {
          if (validateNull(temp.judgeresult)) {
            this.$tap.alert('请填写项目成员评价-评价结果！', 'warning')
            return false
          }
        }
      }
      return true
    },
    /** PMO标准化 **/
    saveInfo(resolve, reject) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 保存时同时保存项目成员评价子表信息
          this.$set(this.model, 'performancelist', this.$refs.performanceRef.datas)
          putAction(this.url.edit, this.model)
            .then((res) => {
              if (res.success) {
                this.$emit('refresh')
                resolve()
              } else {
                this.$tap.alert(res.message, 'warning')
                reject()
              }
            })
            .catch((err) => {
              this.$tap.alert('修改项目信息失败，请联系系统管理员', 'warning')
              reject()
            })
        } else {
          this.$tap.alert('请填写所有必填字段!', 'warning')
          reject()
        }
      })
    },
    /** 提交前执行 */
    beforeSubmit() {
      if (!this.model.projectname) {
        this.$tap.alert('项目不能为空!', 'warning')
        return false
      }
      // 保存时同时保存项目成员评价子表信息
      this.$set(this.model, 'performancelist', this.$refs.performanceRef.datas)
      return true
    },
    /** 重写执行新增提交，为了获取id */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            // 保证在刷新数据后再打开中标详情页
            this.queryData(res.result.id).then(() => {
              this.loaded()
              this.afterSubmit()
            })
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 查询编码 */
    doQueryCode() {
      if (this.url.queryCodeList) {
        getAction(this.url.queryCodeList, {}).then((res) => {
          if (res.success) {
            this.codeModel = res.result
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    async recordUpload() {
      let param = {
        qry_sourcetype: 'MpmProject',
        qry_sourceapp: 'mpm',
        qry_sourceid: this.projectinfo.id,
        qry_state: '1'
      }
      return getAction(this.url.meetList, param).then((res) => {
        if (res.success && res.result.dataList.length > 0) {
          for (let i = 0; i < res.result.dataList.length; i++) {
            if (res.result.dataList[i].dispmeettypeid === '销售项目会议/复盘会' && (res.result.dataList[i].recorduploaded === true || res.result.dataList[i].audiouploaded)) {
              return true
            }
          }
          this.$tap.alert('未召开复盘会,不允许提交复盘报告！', 'warning')
          return false
        } else {
          this.$tap.alert('未召开复盘会,不允许提交复盘报告！', 'warning')
          return false
        }
      })
    },
    clearOldReview() {
      this.$set(this.model, 'enddate', null)
      this.$set(this.model, 'achievements', null)
      this.$set(this.model, 'iswinbid', null)
      this.$set(this.model, 'summary', null)
      this.$set(this.model, 'planningtarget', null)
      this.$set(this.model, 'customerrelationanalysis', null)
      this.$set(this.model, 'competitoranalysis', null)
      this.$set(this.model, 'customerrelation', null)
      this.$set(this.model, 'guidebeforebid', null)
      this.$set(this.model, 'submitbidingdocument', null)
      this.$set(this.model, 'projectmanagement', null)
      this.assignModel()
    },
    async getBidGuideInfo() {
      this.connectBid = false
      let param = {
        id: this.model.id,
        projectcode: this.model.projectcode,
        purchasepattern: this.model.purchasepattern
      }
      return await getAction(this.url.getBidGuideInfo, param).then(async (res) => {
        if (res.success) {
          this.connectBid = res.result
          let a = await this.$refs.winBidInfoRef.loadData()
          return a
        } else {
          this.$tap.alert('同步中标信息失败，请前往投标系统填写！', 'warning')
          return false
        }
      })
    },
    aftergetproject() {
      const { projectid, projectcode } = this.model
      var params = {
        qry_projectcode: projectcode
      }
      getAction('/mpm/projectReview/judegEndTpye', params).then((res) => {
        if (res.success) {
          if (res.result.endtype === '1') {
            this.$set(this.model, 'endtype', '1')
          } else {
            this.$set(this.model, 'endtype', '0')
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    }
  },
  created() {
    window.addEventListener('resize', this.resizeHandler)
  },
  destroyed() {
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>
<style lang="scss" scoped>
.text-hover:hover {
  color: #0a6ed2;
  cursor: pointer;
}
</style>
